// 游戏默认数据
const gameData = {
    gameStatus: { status: 0, round: 0, roundStatus: 0 },
    openCards: [],
    darkCards: [],
    players: {
        self: { account: '', name: '', score: 0, cards: [] },
        others: []
    },
    selectedCards : []
};

// 获取游戏状态接口调用
async function fetchGameStatus() {
    try {
        const response = await fetch('/zhualaoer/getGameStatus');
        const result = await response.json();
        if (result.code==200) {
            return result.data;
        }else if(result.code==500){
            // 未登录，重定向到登录页面
            window.location.href = 'index.html';
        } 
        console.log('获取游戏状态失败:', result.message);
        return null;
    } catch (error) {
        console.log('获取游戏状态接口异常:', error);
        return null;
    }
}

// 获取游戏信息接口调用
async function fetchGameInfo() {
    try {
        const response = await fetch('/zhualaoer/getGameInfo');
        const result = await response.json();
        if (result.code==200) {
            return result.data;
        }else if(result.code==500){
            // 未登录，重定向到登录页面
            window.location.href = 'index.html';
        }   
        console.log('获取游戏信息失败:', result.message);
        return null;
    } catch (error) {
        console.log('获取游戏信息接口异常:', error);
        return null;
    }
}

// 定时检查游戏状态
async function checkGameStatus() {
    console.log('检查游戏状态');
    const newStatus = await fetchGameStatus();
    const prepareButton = document.getElementById('prepareButton');

    if(newStatus.status ==2 ){
        prepareButton.style.display = 'none';
    }else if(newStatus.status == 3){
        prepareButton.style.display = 'block';
    }

    if(newStatus.status==0){ 
        //初始化游戏状态和回合数
        gameReload()
        document.getElementById('gameRound').textContent = `当前回合 ：第${newStatus.round}回合`;
        document.getElementById('gameInfo').textContent = '请准备游戏';
        // 准备按钮点击事件
        const prepareButton = document.getElementById('prepareButton');
        // 隐藏出牌按钮
        const playButton = document.getElementById('playCardBtn');
        playButton.style.display = '';
        // 隐藏准备按钮
        prepareButton.style.display = '';
        // 隐藏加载遮罩
        document.getElementById('loading-mask').style.display = 'none';
    }

    if(newStatus.status==1 && gameData.gameStatus.status != 1){
        document.getElementById('gameInfo').textContent = '等待全部玩家准备就绪';
        document.getElementById('gamePot').textContent = '底分: 10';
        // 隐藏出牌按钮
        const playButton = document.getElementById('playCardBtn');
        gameData.gameStatus.status = newStatus.status;
        // 隐藏加载遮罩
        document.getElementById('loading-mask').style.display = 'none';
    }

    if(newStatus.status==2 && gameData.gameStatus.status != 2){
        //全部玩家都准备好了，开始第一回合。
        gameData.gameStatus.status = newStatus.status;
        gameData.gameStatus.round = newStatus.round;
        gameData.gameStatus.roundStatus = newStatus.roundStatus;
        document.getElementById('gameRound').textContent = `当前回合 ：第${newStatus.round}回合`;
        document.getElementById('gameInfo').textContent = '等待全部玩家出牌';
        document.getElementById('gamePot').textContent = '底分: ' + newStatus.round*10;
        const gameInfo = await fetchGameInfo();
        initGame(gameInfo);
        //从第2回合开始到第4回合，要移除公共区域round - 1 张，比如第4回合需要移除 最后3张牌
        if(newStatus.round >=2 && newStatus.round <=5){
            let publicCards = document.getElementById('publicCards');
            //移除最后newStatus.round - 1 张牌
            for(let i = 0; i < newStatus.round - 1; i++){
                publicCards.removeChild(publicCards.lastChild);
            }
            if(newStatus.round == 5){
                //移除最后一张牌
                publicCards.innerHTML =''
            }
        } 
        // 隐藏加载遮罩
        document.getElementById('loading-mask').style.display = 'none';
    }

    if(newStatus.status==2 && gameData.gameStatus.status == 2){
        //结算页面
        if(newStatus.roundStatus == 3 && gameData.gameStatus.roundStatus != 3){
            document.getElementById('gameInfo').textContent = '等待全部玩家确认结算';
            gameData.gameStatus.roundStatus = newStatus.roundStatus
            const sett = await fetchGetSett();
            //游戏结束，显示结算模块
            showResultModal(newStatus.round,sett);
            // 隐藏加载遮罩
            document.getElementById('loading-mask').style.display = 'none';
        }

        if(newStatus.roundStatus == 0 && gameData.gameStatus.roundStatus != 0){
            document.getElementById('gameInfo').textContent = '等待发牌';
            gameData.gameStatus.round = newStatus.round;
            gameData.gameStatus.roundStatus = newStatus.roundStatus;
        }

        //新一回合发牌发牌
        if(newStatus.roundStatus == 1 && gameData.gameStatus.roundStatus != 1){
            gameData.gameStatus.round = newStatus.round;
            gameData.gameStatus.roundStatus = newStatus.roundStatus;
            document.getElementById('gameRound').textContent = `当前回合 ：第${newStatus.round}回合`;
            document.getElementById('gamePot').textContent = '底分: ' + newStatus.round*10
            document.getElementById('gameInfo').textContent = '等待全部玩家出牌';
            const gameInfo = await fetchGameInfo();
            initGame(gameInfo);

            //从第2回合开始到第4回合，要移除公共区域round - 1 张，比如第4回合需要移除 最后3张牌
            if(newStatus.round >=2 && newStatus.round <=5){
                let publicCards = document.getElementById('publicCards');
                //移除最后newStatus.round - 1 张牌
                for(let i = 0; i < newStatus.round - 1; i++){
                    publicCards.removeChild(publicCards.lastChild);
                }
                if(newStatus.round == 5){
                    //移除最后一张牌
                    publicCards.innerHTML =''
                }
            } 
            // 隐藏出牌按钮
            const playButton = document.getElementById('playCardBtn');
            playButton.style.display = '';
            // 隐藏加载遮罩
            document.getElementById('loading-mask').style.display = 'none';
        }
          
    }
}

async function gameReload(){
    // 初始化游戏状态和回合数
    gameData.gameStatus.status = 0;
    gameData.gameStatus.round = 0;
    gameData.gameStatus.roundStatus = 0;
    // 初始化牌局信息
    gameData.openCards = [];
    gameData.darkCards = [];
    // 初始化玩家信息
    gameData.players.self = { account: '', name: '', score: 0, cards: [] };
    gameData.players.others = [];
}

async function fetchGetSett(){
    try {
        const response = await fetch('/zhualaoer/getSett');
        const result = await response.json();
        if (result.code==200) {
            return result.data;
        }else if(result.code==500){
            // 未登录，重定向到登录页面
            window.location.href = 'index.html';
        } 
        console.log('获取结算信息失败:', result.message);
        return null;
    } catch (error) {
        console.log('获取结算信息接口异常:', error);
        return null;
    }
}

async function initGame(gameInfo){
  //先清空自己的牌库
  let elementById = document.getElementById('myCards');
  elementById.innerHTML = '';
  //清空选择的牌
  gameData.selectedCards = [];
  //改变自己的牌库
  updateCards(elementById,gameInfo.gameInfo.handCards,true);
  
  //改变公共牌
  gameData.openCards = gameInfo.gameInfo.openCards;
  gameData.darkCards = gameInfo.gameInfo.darkCards;
  //openCards 不需要深拷贝
  let openCards = [...gameInfo.gameInfo.openCards];
  updatePublicCards(gameInfo.gameInfo.darkCards,openCards.reverse(),false);

  //获取本人登录信息
  let userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
  //添加自己的玩家信息和其他玩家信息
    let playUser =  gameInfo.loginUser[userInfo.userAccount];
    document.getElementById('myPlayerInfo').textContent = `玩家${playUser.userAccount}  分数${playUser.score}`;
    //过滤掉自己
    let otherPlayers = gameInfo.loginUser;
    delete otherPlayers[userInfo.userAccount];
    //分别给左边和右边玩家添加信息
    let leftPlayerInfo = document.getElementById('leftPlayerInfo');
    let rightPlayerInfo = document.getElementById('rightPlayerInfo');
    leftPlayerInfo.innerHTML = '';
    rightPlayerInfo.innerHTML = '';
    let i = 0;
    for (const key in otherPlayers) {
        if (i % 2 == 0) {
            leftPlayerInfo.innerHTML += `<div class="player-info">玩家${key}  分数${otherPlayers[key].score}</div>`;
        } else {
            rightPlayerInfo.innerHTML += `<div class="player-info">玩家${key}  分数${otherPlayers[key].score}</div>`;
        }
        i++;
    }

}

//更新公共牌
function updatePublicCards(darkCards,openCards,isInit){
    //先清空公共牌
    let elementById = document.getElementById('publicCards');
    if(isInit){
        elementById.innerHTML = '';
        elementById.innerHTML += `<div class="card deck"></div>`;
        elementById.innerHTML += `<div class="card back"></div>`;
        elementById.innerHTML += `<div class="card back"></div>`;
        elementById.innerHTML += `<div class="card back"></div>`;
        elementById.innerHTML += `<div class="card back"></div>`;
    }else{
        elementById.innerHTML = '';
        elementById.innerHTML += `<div class="card deck"></div>`;
        if(darkCards){
            updateCards(elementById,darkCards,false)
        }else{
            elementById.innerHTML += `<div class="card back"></div>`;
        }
        updateCards(elementById,openCards,false)
    }
}

// 结算模块控制函数
function showResultModal(round,sett) {
    // 更新回合数
    document.getElementById('roundNumber').textContent = `第${round}回合结算`;
    
    // 获取玩家结果容器
    const resultsContainer = document.querySelector('.players-results');
    resultsContainer.innerHTML = '';
    
    //sett 是一个对象 循环sett
    for (const [key, value] of Object.entries(sett)) {
        console.log(key, value);
        //result是一个对象，key是round，value是1或0
        let score = value.result[round]*round*10*(value.result[round] == 1? 1 : 2);
        const resultDiv = document.createElement('div');
        resultDiv.className = `player-result ${value.result[round] == 1? 'winner' : ''}`;
        // 玩家名称
        const nameDiv = document.createElement('div');
        //获取自己的会员信息
        // 从会话存储中获取用户信息
        const userAccount = JSON.parse(sessionStorage.getItem('userInfo')).userAccount;
        //是自己名称标红
        nameDiv.className = `player-name ${userAccount == key ? 'red' : ''}`;
        nameDiv.textContent ="玩家"+ key;

        // 玩家卡牌
        const cardsDiv = document.createElement('div');
        cardsDiv.className = 'player-cards-small';
        
        let card ;
        //获取当前回合的公共牌  
        if(round<=3){
            card = gameData.openCards[round-1]
            const suitInfo = convertSuit(card.suit);
            const rankInfo = convertRank(card.rank);
            cardsDiv.innerHTML += `<div class="card small-card front ${suitInfo.class}" data-rank="${rankInfo}" data-suit="${suitInfo.symbol}">${suitInfo.symbol}</div>`;
        }else if(round == 4){
            card = gameData.darkCards[0]
            const suitInfo = convertSuit(card.suit);
            const rankInfo = convertRank(card.rank);
            cardsDiv.innerHTML += `<div class="card small-card front ${suitInfo.class}" data-rank="${rankInfo}" data-suit="${suitInfo.symbol}">${suitInfo.symbol}</div>`;
        }
        
        value.handCards.forEach(handCard => {
            const suitInfo = convertSuit(handCard.suit);
            const rankInfo = convertRank(handCard.rank);
            cardsDiv.innerHTML += `<div class="card small-card front ${suitInfo.class}" data-rank="${rankInfo}" data-suit="${suitInfo.symbol}">${suitInfo.symbol}</div>`;
        });

        // 玩家得分
        const scoreDiv = document.createElement('div');
        scoreDiv.className = 'player-score';
        scoreDiv.textContent = `得分: ${score}`;
        
        // 组装玩家结果
        resultDiv.appendChild(nameDiv);
        resultDiv.appendChild(cardsDiv);
        resultDiv.appendChild(scoreDiv);
        resultsContainer.appendChild(resultDiv);
    }
    
    // 显示结算模块
    document.getElementById('result-modal').style.display = 'flex';
}

//更新牌库
function updateCards(elementById,cards,isSelf){
    //改变自己的牌库
    cards.forEach(card => {
        const suitInfo = convertSuit(card.suit);
        const rankInfo = convertRank(card.rank);
        elementById.innerHTML += `<div class="card front ${suitInfo.class}" data-rank="${rankInfo}" data-suit="${suitInfo.symbol}">${suitInfo.symbol}</div>`;
    });
    if(isSelf){
        //给elementById下的卡牌添加点击事件
        elementById.querySelectorAll('.card').forEach(card => {
            card.addEventListener('click', function() {
                const isSelected = this.classList.contains('selected');
                            
                if (isSelected) {
                    // 取消选中
                    this.classList.remove('selected');
                    gameData.selectedCards = gameData.selectedCards.filter(c => c !== this);
                } else {
                    // 检查是否超过最大选择数量
                    let maxSelect = gameData.gameStatus.round <= 4 ? 2 : 3;
                    if (gameData.selectedCards.length < maxSelect) {
                        this.classList.add('selected');
                        gameData.selectedCards.push(this);
                    } else {
                        alert(`当前回合只能选择${maxSelect}张卡牌`);
                    }
                }
            });
        });
    }
}

//更新为背面牌,参数id，和数量int ,根据int循环更新为背面牌
function updateDarkCards(id,int){
    //先清空自己的牌库
    document.getElementById(id).innerHTML = '';
    //改变自己的牌库
    for (let i = 0; i < int; i++) {
        document.getElementById(id).innerHTML += `<div class="card back"></div>`;
    }
}

// 立即执行一次
checkGameStatus();
// 每秒执行一次
setInterval(checkGameStatus, 1000);